﻿#include "ThreadShowChangeFiles.h"
#include <iostream>

QHash<QString, QDateTime> ThreadShowChangeFiles::foreachPath(QString& dirPath) {
	QHash<QString, QDateTime> result;
	QDir dir(dirPath);
	QFileInfoList fileInfos = dir.entryInfoList( );
	QVector<QString> subInfo;
	for( auto& info : fileInfos ) {
		QString fileName = info.fileName( );
		if( fileName == "." || fileName == ".." )
			continue;
		QString absoluteFilePath = info.absoluteFilePath( );
		QDateTime dateTime = QDateTime::currentDateTime( );
		QDateTime changeTime = info.metadataChangeTime( );
		QDateTime addDays = currentDateTimeToCompleterDateTime(changeTime);
		if( addDays <= dateTime ) {
			fileChangeInfo.insert(absoluteFilePath, changeTime);
		}
		if( info.isDir( ) ) {
			subInfo.append(absoluteFilePath);
		}
	}
	for( auto& subDirInfo : subInfo ) {
		QHash<QString, QDateTime> dateTimes = foreachPath(subDirInfo);
		for( auto iterator = dateTimes.begin( ), end = dateTimes.end( );iterator != end;++iterator ) {
			fileChangeInfo.insert(iterator.key( ), iterator.value( ));
		}
	}
	return result;
}

ThreadShowChangeFiles::ThreadShowChangeFiles(QObject* parent): QThread{ parent } {}

void ThreadShowChangeFiles::run( ) {
	// 队列 id
	static int ququeId = 10;
	fileChangeInfo.clear( );
	QFileInfo srcInfo(srcFilePath);
	if( srcInfo.exists( ) ) {
		QDateTime dateTime = QDateTime::currentDateTime( );
		QDateTime changeTime = srcInfo.metadataChangeTime( );
		QDateTime addDays = currentDateTimeToCompleterDateTime(changeTime);
		if( addDays <= dateTime ) {
			fileChangeInfo.insert(srcFilePath, changeTime);
		}
		if( srcInfo.isDir( ) ) {
			QHash<QString, QDateTime> dateTimes = foreachPath(srcFilePath);
			for( auto iterator = dateTimes.begin( ), end = dateTimes.end( );iterator != end;++iterator ) {
				fileChangeInfo.insert(iterator.key( ), iterator.value( ));
			}
		}
	}
	QMutexLocker locker(getShowMutexObj(  ));
	locker.unlock(  );
	emit overTask(&fileChangeInfo, &srcFilePath);
}
